import { request } from '@/utils'

export interface CategoryListItem {
  id: string
  name: string
  description?: string
  type: string
  color?: string
  sortNo: number
  parentId?: string
  children?: CategoryListItem[]
  isLeaf?: boolean
  itemCount?: number
}

export interface CategoryDetails extends CategoryListItem {
  createdTime: string
  updatedTime: string
}

export interface CategoryRequest {
  name: string
  description?: string
  type: string
  color?: string
  sortNo?: number
  parentId?: string
}

export interface CategoryListQuery {
  type?: string
}

export interface DragRequest {
  targetId: string
  dropType: 'before' | 'after' | 'inner'
}

/**
 * 分类API - 收藏模块使用 type=COLLECT
 */
export const categoryApi = {
  /**
   * 获取分类列表
   */
  async list(params?: CategoryListQuery) {
    let url = '/category/list'
    if (params?.type) {
      url += `?type=${params.type}`
    }
    const response = await request.get<CategoryListItem[]>(url)
    return response.data
  },

  /**
   * 获取分类树形结构列表
   */
  async tree(params?: CategoryListQuery) {
    let url = '/category/list'
    if (params?.type) {
      url += `?type=${params.type}`
    }
    const response = await request.get<CategoryListItem[]>(url)
    return response.data
  },

  /**
   * 获取分类详情
   */
  async detail(id: string) {
    const response = await request.get<CategoryDetails>(`/category/${id}`)
    return response.data
  },

  /**
   * 创建分类
   */
  async create(data: CategoryRequest) {
    const response = await request.post<CategoryDetails>('/category/create', data)
    return response.data
  },

  /**
   * 更新分类
   */
  async update(id: string, data: CategoryRequest) {
    const response = await request.put<CategoryDetails>(`/category/${id}`, data)
    return response.data
  },

  /**
   * 删除分类
   */
  async delete(id: string) {
    const response = await request.delete(`/category/${id}`)
    return response.data
  },

  /**
   * 拖拽分类
   */
  async drag(id: string, data: DragRequest) {
    const response = await request.put(`/category/${id}/drag`, data)
    return response.data
  }
}
